#!/bin/sh
# Job yaml can send below ENVIRONMENT VARIABLES to me
# - ssh_pub_key
# - tmout
# END ENVIRONMENT VARIABLES

SCRIPT_DIR=$(dirname $(realpath $0))
PROJECT_DIR=$(dirname $SCRIPT_DIR)

. $PROJECT_DIR/lib/job.sh
load_job_vars LKP_SERVER sched_host sched_port sshr_server_host sshr_server_port sshr_port_base sshr_port_len JUMPER_HOST

. $PROJECT_DIR/lib/http.sh
. $PROJECT_DIR/lib/env.sh
. $PROJECT_DIR/lib/email.sh
. $PROJECT_DIR/lib/create_script_rootfs.sh

[ -n "$sshr_server_host" ] || {
	[ -n "$LKP_SERVER" ] && sshr_server_host="$LKP_SERVER"
	[ -n "$sched_host" ] && sshr_server_host="$sched_host"
}

[ -n "$sshr_server_port" ]   || sshr_server_port=5051
[ -n "$sshr_port_len" ]      || sshr_port_len=2000
[ -n "$sshr_port_base" ]     || sshr_port_base=21000
[ -n "$tmout" ]              || tmout=3600

set_login_tmout()
{
	# set the idle wait time(TMOUT) of linux system, set 0 is prevent timeout exit
	echo "export TMOUT=$tmout" >> /etc/profile
}

set_term()
{
	# $TERM be set "tmux-256color" in tmux, this will raise:
	# 	setterm: tmux-256color: unknown terminal type
	echo "export TERM='linux'" >> /etc/profile
}

generate_key_files()
{
    # Generate RSA key (if not already present)
    [ -f /etc/ssh/ssh_host_rsa_key ] || ssh-keygen -t rsa -b 4096 -N '' -f /etc/ssh/ssh_host_rsa_key

    # Generate ECDSA key
    [ -f /etc/ssh/ssh_host_ecdsa_key ] || ssh-keygen -t ecdsa -b 521 -N '' -f /etc/ssh/ssh_host_ecdsa_key

    # Generate ED25519 key
    [ -f /etc/ssh/ssh_host_ed25519_key ] || ssh-keygen -t ed25519 -N '' -f /etc/ssh/ssh_host_ed25519_key

    # Set proper permissions
    chmod 600 /etc/ssh/ssh_host_*_key
    chmod 644 /etc/ssh/ssh_host_*_key.pub
}

run_ssh()
{
	umask 0077
	mkdir -p /root/.ssh/sshr

	[ -n "$ssh_pub_key" ] &&
	echo "$ssh_pub_key" >> /root/.ssh/authorized_keys

	if has_cmd systemctl && test -e /etc/ssh/ssh_host_rsa_key; then
		systemctl start sshd
	else
		# Minimal (docker) rootfs
		generate_key_files
		sshd_path=$(cmd_path sshd)
		$sshd_path
	fi
}

reconnect_every_half_minute()
{
	while true
	do
		ssh -o StrictHostKeyChecking=no -o ExitOnForwardFailure=yes -o TCPKeepAlive=yes \
			-Nf -R $port:localhost:22 sshr@"$sshr_server_host" -p "$sshr_server_port" -i /root/.ssh/sshr/id_rsa &>/dev/null
		sleep 30
	done
}

set_port()
{
	[ -n "$ssh_pub_key" ] || return

	chmod 600 /root/.ssh/sshr/id_rsa
	for i in $(seq 1 10)
	do
		if [ -n "$sshr_static_port" ] && [ "$sshr_static_port" -ge 23900 ] && [ "$sshr_static_port" -le 23999 ];then
			port="$sshr_static_port"
		else
			port=$(($(date +%s%N)%$sshr_port_len+$sshr_port_base))
		fi

		ssh -o StrictHostKeyChecking=no -o ExitOnForwardFailure=yes -o TCPKeepAlive=yes \
			-Nf -R $port:localhost:22 sshr@"$sshr_server_host" -p "$sshr_server_port" -i /root/.ssh/sshr/id_rsa > ssh_msg 2>&1

		[ $? -eq 0 ] && {
			reconnect_every_half_minute &
			return
		}
	done
	ssh_error_message="$(cat -e ssh_msg)"
	echo $ssh_error_message
	port=""
}

mount_user_home()
{
	[ -n "$secrets_smb_user" ] || return 0
	[ -n "$secrets_smb_pass" ] || return 0

	# the mount point in testbox is set the same as its home dir in the account-vm
	[[ -d "/home/$secrets_smb_user" ]] || mkdir -p "/home/$secrets_smb_user"
	mount.cifs //"$JUMPER_HOST"/"$secrets_smb_user" "/home/$secrets_smb_user" \
		   -o username="$secrets_smb_user",password="$secrets_smb_pass"
}

run_email()
{
	deadline=$(date -d "$runtime seconds" +"%Y-%m-%d %H:%M:%S")
	local my_email="$secrets_my_email"

	if [ -n "$port" ]; then
		send_email "borrow_success"
	else
		send_email "borrow_failed"
	fi
}

create_rootfs "sshd"
set_login_tmout
set_term
run_ssh
set_port
report_ssh_info "$port" "${ssh_error_message}"
mount_user_home
# run_email
